var AjaxCrud = QualityCheck.AjaxCRUD;
var serverUrl = QualityCheck.GPUD.ServiceConfig;
var currentPage = 1;
var pageSize = 10;
var map = null;
var toolbar = null;
var scale = null;
var cachedatas = null;
var editorTool = {};
var circle = {};
var mySlider;
var placeSearch = null;
var style = {
        color:'#FC740F',
        fillColor:'#FC740F',
        fillOpacity:0.2,
        weight:3
    };
var style1 = {
        color:'red',
        fillColor:'blue',
        fillOpacity:0.2,
        weight:3
    };
var style2 = {
        color:'blue',
        fillColor:'yellow',
        fillOpacity:0.2,
        weight:3
    };
var style3 = {
        color:'blue',
        fillColor:'red',
        fillOpacity:0.2,
        weight:3
    };
var styleselect = {
        color:'blue',
        fillColor:'blue',
        fillOpacity:0.2,
        weight:3
    };
$(function(){
	var usercode = $("#user-name",parent.parent.document).attr("code");
	var userkey = $("#user-name",parent.parent.document).attr("key");
	var usertype = $("#user-name",parent.parent.document).attr("usertype");
	keyCheck(usercode,usertype,userkey,function(){
		initPages();
		window.onresize = function () {
			initPages();
		};
		pageBtns();
		initMap();
		getSchoolFence();
		getStudentFence();
	});
});
function initMap(){
	map = new AMap.Map("map",{
		level:15,//设置地图缩放级别
		resizeEnable: true
	});
	map.plugin(["AMap.ToolBar","AMap.OverView","AMap.Scale"],function(){ 
		toolbar = new AMap.ToolBar();
		toolbar.autoPosition=false; //加载工具条 
		map.addControl(toolbar);  	
		scale = new AMap.Scale(); //加载比例尺
		map.addControl(scale);
	});
	map.setDefaultCursor("url(http://developer.amap.com/wp-content/uploads/2014/06/closedhand.cur),pointer");
	$(".amap-logo").hide();
	$(".amap-copyright").hide();
	$(".amap-container").css("position","absolute");
	getNowCity();
	
	var autoOptions = {
        input: "keyword-search"
    };
	var auto = new AMap.Autocomplete(autoOptions);
    placeSearch = new AMap.PlaceSearch({
    	pageSize: 5,
        pageIndex: 1,
        map: map,
        panel: "res-panel"
    });  //构造地点查询类
    AMap.event.addListener(auto, "select", function(e){
    	placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name);  //关键字查询查询
    });
}
function getNowCity(){
	  //加载城市查询插件
  AMap.service(["AMap.CitySearch"], function() {
      //实例化城市查询类
      var citysearch = new AMap.CitySearch();
      //自动获取用户IP，返回当前城市
      citysearch.getLocalCity(function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
              if (result && result.city && result.bounds) {
                  var citybounds = result.bounds;
                  //地图显示当前城市
                  map.panTo(new AMap.LngLat(citybounds.getCenter().lng,citybounds.getCenter().lat));
              }
          }
      });
  });
}
function getSchoolFence(){
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var studentCode = $(".students-choice-select",parent.document).attr("studentcode");
	var data = {
			cmd:"getSchoolFenceByStudentCode",
			model:"fence",
			userKey:userKey,
			data:{
				studentcode:studentCode
			},
			remark:""
			
	};
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		for(var key in circle){
			circle[key].setMap(null);
		}
		circle = {};
		if(res.result == 1 && res.data != undefined && res.data != ""){
			schoolfenceData = res.data;
			var fencepoint = res.data.center.split(",");
			var x = fencepoint[0] * 1;
			var y = fencepoint[1] * 1;
			var fenceradius = res.data.radius;
			addCircle("schoolfence",new AMap.LngLat(x,y),fenceradius*100,style);
		}else{
			processError("学校围栏加载失败！");
		}
	},null,null);
}
function getStudentFence(){
	processBegin("数据加载中···");
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var studentCode = $(".students-choice-select",parent.document).attr("studentcode");
	var data = {
			cmd:"getFenceByStudentCode",
			model:"fence",
			userKey:userKey,
			data:{
				studentcode:studentCode
			},
			remark:""
			
	};
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		for(var key in circle){
			if(key != "schoolfence"){
				circle[key].setMap(null);
			}
		}
		if(res.result == 1){
			processEnd("数据加载成功");
			var list = res.data;
			for(var i = 0; i < list.length; i++){
				var latlngStr = list[i].fencepoint;
				var listArr = latlngStr.split(",");
				if(list[i].type == 1 || list[i].type == "1"){
					addCircle(list[i].fencecode,new AMap.LngLat(listArr[0]*1,listArr[1]*1),list[i].fenceradius*100,style1,list[i]);
				}else if(list[i].type == 2 || list[i].type == "2"){
					addCircle(list[i].fencecode,new AMap.LngLat(listArr[0]*1,listArr[1]*1),list[i].fenceradius*100,style2,list[i]);
				}else if(list[i].type == 3 || list[i].type == "3"){
					addCircle(list[i].fencecode,new AMap.LngLat(listArr[0]*1,listArr[1]*1),list[i].fenceradius*100,style3,list[i]);
				}
			}
		}else{
			processError("学生围栏加载失败！");
		}
		showFenceList(res);
	},null,null);
}
function showFenceList(res){
	var content = "<div class=\"data-trs-show\" fencecode = 'schoolfencebtn' latlng='"+schoolfenceData.center+"'>" +
					"<div class=\"pdata-name\" style='width:180px;' title='"+schoolfenceData.name+"'>"+substr(schoolfenceData.name,11)+"</div>" +
					"<div class=\"pdata-class\" style='width:180px;'>学校围栏</div>" +
					"<div class=\"pdata-add\" style='width:180px;' title='"+schoolfenceData.adress+"'>"+substr(schoolfenceData.adress,11)+"</div>" +
				"</div>";
	if(res.result == 1 && res.data != undefined && res.data != ""){
		var list = res.data;
		for(var i = 0; i < list.length; i++){
			if(list[i].type == "1" || list[i].type == 1){
				list[i].type = "进出";
			}else if(list[i].type == "2" || list[i].type == 2){
				list[i].type = "进入";
			}else if(list[i].type == "3" || list[i].type == 3){
				list[i].type = "离开";
			}
			if(list[i].remark == null || list[i].remark == "null"){
				list[i].remark = "";
			}
			var stuName = $(".students-choice-select",parent.document).attr("name");
			content += "<div class=\"data-trs-show\" fencecode='"+ list[i].fencecode +"' latlng = \""+list[i].fencepoint+"\">" +
			"<div class=\"pdata-name\" title='"+list[i].remark+"' style='width:180px;'>"+substr(list[i].remark,11)+"</div>" +
//							"<div class=\"pdata-img\">" +
//							"</div>" +
			"<div class=\"pdata-class\" style='width:180px;'>类型：" + list[i].type + "</div>" +
			"<div class=\"pdata-add\" title=\""+stuName+"\" style='width:180px;'>" + substr(stuName + "的" + list[i].remark + "围栏",13) + "</div>" +
			"</div>";
		}
	}else{
		content += "<div class='no-res-show'></div>";
	}
	$(".left-datas-show").empty();
	$(".left-datas-show").append(content);
	
	$(".data-trs-show").unbind("click");
	$(".data-trs-show").click(function(){
		$(".data-trs-show").removeClass("data-trs-show-selected");
		$(this).addClass("data-trs-show-selected");
		var name = $(this).attr("fencecode");
		var latlngStr = $(this).attr("latlng");
		var x = latlngStr.split(",")[1] * 1;
		var y = latlngStr.split(",")[0] * 1;
		map.panTo(new AMap.LngLat(y,x));
		clearSelect(name);
		if(name != "schoolfencebtn"){
			circle[name].setOptions({
				fillColor:styleselect.fillColor,
				strokeColor:styleselect.color
			});
			for(var key in editorTool){
				editorTool[key].close();
			}
			//添加编辑控件
			if(editorTool[name] == undefined){
				map.plugin(["AMap.CircleEditor"], function() {
					editorTool[name] = new AMap.CircleEditor(map, circle[name]);
				});
			}
			fenceEditBtnClick(circle[name],circle[name].getExtData().attr,editorTool[name]);
		}else{
			$(".index-dialog").hide();
			for(var key in editorTool){
				editorTool[key].close();
			}
			clearAll();		
			$(".data-trs-show").removeClass("data-trs-show-selected");
		}
	});
}
function drawCircle(name,latlng,radius,options){
	if(circle[name]){
		circle[name].setMap(null);
		circle[name] = null;
	}
	circle[name] = new AMap.Circle({
		id:name,
		center:latlng,//圆心，基点
		radius:radius,//半径
		strokeColor: options.color,//线颜色
		strokeOpacity: 1,//线透明度
		strokeWeight: 3,//线宽
		fillColor: options.fillColor,//填充颜色
		fillOpacity: 0.2//填充透明度
	});
	circle[name].setMap(map);
	//添加编辑控件
	map.plugin(["AMap.CircleEditor"], function() {
		editorTool["new"] = new AMap.CircleEditor(map, circle["new"]);	
		editorTool["new"].open();
		AMap.event.addListener(editorTool["new"], "adjust", function(e){
			if(Math.round(e.radius) < 100){
				e.radius = 100;
			}else if(Math.round(e.radius) > 500){
				e.radius = 500;
			}else{
				e.radius = (Math.round(e.radius/100))*100;
			}
			mySlider.setValue(e.radius);
			$("#fence-radius").val(Math.round(e.radius));
		});
		AMap.event.addListener(editorTool["new"], "move", function(e){
			var lng = e.lnglat.lng;
			var lat = e.lnglat.lat;
			var latLng =lng + "," + lat;
			$("#fence-latlng").val(latLng);
		});
	});
}
function addCircle(name,latlng,radius,options,attr){
	if(circle[name]){
		circle[name].setMap(null);
		circle[name] = null;
	}
	circle[name] = new AMap.Circle({
		id:name,
		center:latlng,//圆心，基点
		radius:radius,//半径
		strokeColor: options.color,//线颜色
		strokeOpacity: 1,//线透明度
		strokeWeight: 3,//线宽
		fillColor: options.fillColor,//填充颜色
		fillOpacity: 0.2//填充透明度
	});
	circle[name].setExtData({attr:attr});
	circle[name].setMap(map);
	AMap.event.addListener(circle[name],"click",function(e){
		$(".fence-res-data tr").removeClass("fence-res-data-select");
		$(".fence-res-data tr[fencecode='"+name+"']").addClass("fence-res-data-select");
		clearSelect(name);
		circle[name].setOptions({
			fillColor:styleselect.fillColor,
			strokeColor:styleselect.color
		});
		//添加编辑控件
		if(editorTool[name] == undefined){
			map.plugin(["AMap.CircleEditor"], function() {
				editorTool[name] = new AMap.CircleEditor(map, circle[name]);
			});
		}
		editCircle(circle[name],circle[name].getExtData().attr,editorTool[name]);
	});
}
function clearAll(){
	for(var key in circle){
		if(key != "schoolfence"){
			if(circle[key].getExtData().attr.type == "进出"){
				circle[key].setOptions({
					fillColor:style1.fillColor,
					strokeColor:style1.color
				});
			}else if(circle[key].getExtData().attr.type == "进入"){
				circle[key].setOptions({
					fillColor:style2.fillColor,
					strokeColor:style2.color
				});
			}else if(circle[key].getExtData().attr.type == "离开"){
				circle[key].setOptions({
					fillColor:style3.fillColor,
					strokeColor:style3.color
				});
			}
		}
	}
}
function clearSelect(name){
	for(var key in circle){
		if(key != name && key != "new" && key != "schoolfence"){
			if(circle[key].getExtData().attr.type == "进出"){
				circle[key].setOptions({
					fillColor:style1.fillColor,
					strokeColor:style1.color
				});
			}else if(circle[key].getExtData().attr.type == "进入"){
				circle[key].setOptions({
					fillColor:style2.fillColor,
					strokeColor:style2.color
				});
			}else if(circle[key].getExtData().attr.type == "离开"){
				circle[key].setOptions({
					fillColor:style3.fillColor,
					strokeColor:style3.color
				});
			}
//			if(editorTool[key]){
//				editorTool[key].close();
//			}
		}
	}
}
function editCircle(circle,options,edit){
	$(".fence-edit-btn").unbind("click");
	$(".fence-edit-btn").click(function(){
		fenceEditBtnClick(circle,options,edit);
	});
	$(".fence-delete-btn").unbind("click");
	$(".fence-delete-btn").click(function(){
		var fencecode = options.fencecode;
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var studentcode = $(".students-choice-select",parent.document).attr("studentcode");
		deleteBox("确定要删除吗？",function(){
			deleteStudentFence(circle,fencecode,studentcode,userKey);
		});
	});
}
function fenceEditBtnClick(circle,options,edit){
	showEditDialog(options);
	map.plugin(["AMap.CircleEditor"], function(){
		edit = editorTool[name] = new AMap.CircleEditor(map, circle);
		edit.open();
		AMap.event.addListener(edit, "adjust", function(e){
			if(Math.round(e.radius) < 100){
				e.radius = 100;
			}else if(Math.round(e.radius) > 500){
				e.radius = 500;
			}else{
				e.radius = (Math.round(e.radius/100))*100;
			}
			mySlider.setValue(e.radius);
			$("#fence-radius").val(Math.round(e.radius));
		});
		AMap.event.addListener(edit, "move", function(e){
			var lng = e.lnglat.lng;
			var lat = e.lnglat.lat;
			var latLng =lng + "," + lat;
			$("#fence-latlng").val(latLng);
		});
	});
	mySlider.attachEvent("onChange", function(value){
		circle.setRadius(value);
		$("#fence-radius").val(value);
	});
	mySlider.attachEvent("onSlideEnd", function(value){
		circle.setRadius(value);
		$("#fence-radius").val(value);
	});
	editCircle(circle,options,edit);
}
function showEditDialog(options){
	var contents = "<table class='fence-table'>" +
			"<tr class='table-e'><td>中心点</td><td><input type='text' id='fence-latlng' value = '" + options.fencepoint + "'></td></tr>" +
			"<tr class='table-d'><td>半径</td><td><div id=\"sliderObj\"></div><input type='text' id='fence-radius' value = '" + (options.fenceradius)*100 + "'>米</td></tr>" +
			"<tr class='table-e'><td>类型</td><td><select id='fence-type'>" +
				"<option value='1'>进出</option>" +
				"<option value='2'>进入</option>" +
				"<option value='3'>离开</option>" +
			"</select></td></tr>" +
			"<tr><td>报警方式</td><td><select id='fence-alarmway'>" +
				"<option value='0'>平台</option>" +
				"<option value='1'>平台+短信</option>" +
			"</select></td></tr>" +
			"<tr class='table-d'><td>备注</td><td><input type='text' id='fence-remark' value = '" + options.remark + "'></td></tr>" +
			"</table>" +
			"<div class='fence-edit-save'>保存</div>";
	var obj = {
				disable:false,
				width:315,
				height:305,
				title:"编辑围栏"+options.remark,
				left:325,
				top:50,
				contents:contents
			  };
	showDialog(obj);
	newMySlider();
	mySlider.setValue((options.fenceradius)*100);
	var idx = 0;
	if(options.type == "进出"){
		idx = 0;
	}else if(options.type == "进入"){
		idx = 1;
	}else if(options.type == "离开"){
		idx = 2;
	}
	$("#fence-type option")[idx].selected = true;
	var idy = 0;
	if(options.alarmway == "0"){
		idy = 0;
	}else if(options.alarmway == "1"){
		idy = 1;
	}
	$("#fence-alarmway option")[idy].selected = true;
	$(".fence-edit-save").unbind("click");
	$(".fence-edit-save").click(function(){
		var obj = {};
		obj.fencepoint = $("#fence-latlng").val();
		obj.fenceradius = $("#fence-radius").val()/100;
		obj.remark = encodeURI($("#fence-remark").val());
		obj.type = $("#fence-type option:selected").val();
		obj.alarmway = $("#fence-alarmway option:selected").val();
		obj.studentcode = options.studentcode;
		obj.fencecode = options.fencecode;
		updateStudentFence(obj);
	});
	$(".index-dialog-close").unbind("click");
	$(".index-dialog-close").click(function(){
		$(".index-dialog").hide();
		for(var key in editorTool){
			editorTool[key].close();
		}
		clearAll();		
		$(".data-trs-show").removeClass("data-trs-show-selected");
	});
	
}
function addStudentFence(obj){
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var data = {
			cmd:"addFenceByStudentCode",
			model:"fence",
			userKey:userKey,
			data:obj,
			remark:""
			
	};
	processBegin("正在添加···");
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		if(res.result == 1 && res.data == true){
			processEnd("添加学生围栏成功");
			editorTool["new"].close();
			map.off("click");
			for(var key in circle){
				circle[key].setMap(null);
			}
			closeDialog(function(){
				circle = {};
				getStudentFence();
			});
		}else{
			processError("添加失败");
		}
	},null,null);
}
function updateStudentFence(obj){
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var data = {
			cmd:"updateFenceByStudentCode",
			model:"fence",
			userKey:userKey,
			data:obj,
			remark:""
			
	};
	processBegin("正在保存···");
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		if(res.result == 1 && res.data != null){
			processEnd("修改围栏成功");
			closeDialog(function(){
				getStudentFence();
				for(var key in editorTool){
					editorTool[key].close();
				}
			});
			$(".fence-edit-btn").unbind("click");
			$(".fence-edit-btn").click(function(){
        		alertBox("unedselect","请先选中一个围栏再进行编辑",true);
        	});
		}else{
			processError("修改失败");
		}
	},null,null);
}
function deleteStudentFence(circle,fencecode,studentcode,userKey){
	var data = {
			cmd:"deleteFenceByStudentCode",
			model:"fence",
			userKey:userKey,
			data:{
				fencecode:fencecode,
				studentcode:studentcode
			},
			remark:""
			
	};
	processBegin("正在删除···");
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		if(res.result == 1 && res.data != null){
			processEnd("删除围栏成功");
			closeDialog(function(){
				for(var key in editorTool){
					editorTool[key].close();
				}
				clearAll();
				getStudentFence();
			});
			$(".fence-delete-btn").unbind("click");
			$(".fence-delete-btn").click(function(){
        		alertBox("unedselect","请先选中一个围栏再删除",true);
        	});
		}else{
			processError("删除失败");
		}
	},null,null);
};
function pageBtns(){
	$(".students-choice",parent.document).unbind("click");
	$(".students-choice",parent.document).click(function(){
		$(".students-choice",parent.document).removeClass("students-choice-select");
		$(this).addClass("students-choice-select");
		getSchoolFence();
		getStudentFence();
	});
	$(".fence-add-btn").click(function(){
		var contents = "<table class='fence-table'>" +
		"<tr class='table-e'><td>中心点</td><td><input type='text' id='fence-latlng' value = '" + "" + "'></td></tr>" +
		"<tr class='table-d'><td>半径</td><td><div id=\"sliderObj\"></div><input type=\"text\" id=\"fence-radius\"/>米</td></tr>" +
		"<tr class='table-e'><td>类型</td><td><select id='fence-type'>" +
			"<option value='1'>进出</option>" +
			"<option value='2'>进入</option>" +
			"<option value='3'>离开</option>" +
		"</select></td></tr>" +
		"<tr><td>报警方式</td><td><select id='fence-alarmway'>" +
			"<option value='0'>平台</option>" +
			"<option value='1'>平台+短信</option>" +
		"</select></td></tr>" +
		"<tr class='table-d'><td>备注</td><td><input type='text' id='fence-remark' value = '" + "" + "'></td></tr>" +
		"</table>" +
		"<div class='fence-add-save'>保存</div>";
		var obj = {
					disable:false,
					width:315,
					height:305,
					title:"添加围栏",
					left:325,
					top:50,
					contents:contents
				  };
		showDialog(obj);
		newMySlider();
		var mapClick = AMap.event.addListener(map, "click", function(e){
			var lngd = e.lnglat.lng;
			var latd = e.lnglat.lat;
			var latLngd =lngd + "," + latd;
			$("#fence-latlng").val(latLngd);
			AMap.event.removeListener(mapClick);
			drawCircle('new',new AMap.LngLat(lngd,latd), 100, style);
			mySlider.attachEvent("onChange", function(value){
				circle["new"].setRadius(value);
				$("#fence-radius").val(value);
			});
			mySlider.attachEvent("onSlideEnd", function(value){
				circle["new"].setRadius(value);
				$("#fence-radius").val(value);
			});
			$(".fence-add-save").unbind("click");
			$(".fence-add-save").click(function(){
				var obj = {};
				obj.fencepoint = $("#fence-latlng").val();
    			obj.fenceradius = $("#fence-radius").val()/100;
    			obj.remark = encodeURI($("#fence-remark").val());
    			obj.type = $("#fence-type option:selected").val();
    			obj.alarmway = $("#fence-alarmway option:selected").val();
    			obj.studentcode = $(".students-choice-select",parent.document).attr("studentcode");
				addStudentFence(obj);
			});
			$(".index-dialog-close").unbind("click");
			$(".index-dialog-close").click(function(){
				$(".index-dialog").hide();
				editorTool["new"].close();
				circle["new"].setMap(null);
				
			});
		});
		
	});
	$(".fence-edit-btn").click(function(){
		alertBox("unedselect","请先选中一个围栏再进行编辑",true);
	});
	$(".fence-delete-btn").click(function(){
		alertBox("undeselect","请先选中一个围栏再进行删除操作",true);
	});
	$("#poi-search").click(function(){
		AMap.service(["AMap.PlaceSearch"], function() {
	        //关键字查询
	        placeSearch.search($("#keyword-search").val());
	    });
	});
	$("#clear-search").click(function(){
		placeSearch.clear();
		$("#keyword-search").val("");
	});
}
function newMySlider(){
	mySlider = new dhtmlXSlider({
		parent: "sliderObj",
		linkTo: "fence-radius",
		size: 150,
		value: 5,
		step: 100,
		min: 100,
		max: 500
	});
}
function substr(str,len){
	if(str != undefined){
		if(str.length > len){
			str = str.substring(0,len-2)+"...";
			return str;
		}else{
			return str;
		}
	}else{
		return "";
	}
}
function initPages(){
	var bodyRW = $("#aposition-body",parent.document).width() - $(".left-data-show").width();
	$("#map").width(bodyRW);
	
	var leftDH = $(".left-data-show").height() - 15;
	$(".left-datas-show").height(leftDH);
}